<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Jtail</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.4.0/js/bootstrap.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.4.0/css/bootstrap.min.css" rel="stylesheet">
    <script src="../static/js/index.js"></script>
    <link rel="stylesheet" href="../static/css/index.css">

</head>
<body>
<div class="left">

    <br>
    <label for="dir">当前目录：</label><button> 折叠</button>
    <input type="text" placeholder="请输入目录的路径地址,回车以查看" class="form-control" style="width:100%;font-size:12px;" id="dir" onkeydown="loadAllFiles(event)" value="/">
    <br>
    <div id="files">

    </div>
</div>
<div class="right">
    <div id="log-container" style="height: 800px; overflow-y: scroll; background: #000; color: #aaa; padding: 10px;">
        <div>
        </div>
    </div>
</div>
<div>


</div>


<script>


    var reg = /^http(s?:\/\/(.*))\/.*$/
    var logWsUrl = window.location.href.replace(reg, 'ws$1/log')


    //记录上一个ws信息，以便关闭
    var lastFileKey;
    var lastWebsocket;
    var wsAuth = getCookie('wsAuth');


	function loadLog(fileKey){

	    //debugger
	    if(typeof(lastWebsocket) != "undefined"){
	        lastWebsocket.close();
	        console.log("lastWebsocket.close() ");

	    }
	    if(typeof(lastFileKey) != "undefined"){
	            closeLink(lastFileKey);
	    }

        var url = logWsUrl +"?wsAuth=" + wsAuth + "&fileKey=" + fileKey;
        var websocket = new WebSocket(url);


         //清空页面
        $("#log-container div").empty();
        var loading = "<span class='log-line'>加载中... ...</span><br>"
	    $("#log-container div").append(loading);
        var lineSize = 0
		websocket.onmessage = function(event) {
		    //大于500行时清空页面
		    if(lineSize >500){
		        $("#log-container div").empty();
		        lineSize = 0;
		    }
			// 接收服务端的实时日志并添加到HTML页面中
			$("#log-container div").append(event.data);
			lineSize ++;

			// 滚动条滚动到最低部
			$("#log-container").scrollTop($("#log-container div").height() - $("#log-container").height());

	    }
	    websocket.onopen = function() {
	       console.log("onopen... ");
	       $("#log-container div").empty();
	    }
	    websocket.onclose = function() {
	       console.log("onclose... ");
	       closeLink(fileKey);
	    }

	    lastWebsocket = websocket;
	    lastFileKey = fileKey;


	}

	   function closeLink(fileKey){
            $.ajax({
            type: "POST",
            url: "/closeLink",
            cache: false,  //-- 是否缓存
            async: true,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({"fileKey":fileKey}),
            dataType: "json",
            success: function (e) {
            },
            complete:function(message){
            },
            error: function (message) {
            }
        });
     }

    function getCookie(cookieName) {
        var strCookie = document.cookie;
        var arrCookie = strCookie.split("; ");
        for(var i = 0; i < arrCookie.length; i++){
            var arr = arrCookie[i].split("=");
            if(cookieName == arr[0]){
                return arr[1];
            }
        }
        return "";
    }


    function loadAllFiles(e) {
            var evt = window.event || e;
            if (evt.keyCode == 13) {
               $("#files").empty()
               loadFiles()
            }

    }


    function loadFiles(){
            var dir = $("#dir").val();
            $.ajax({
            type: "POST",
            url: "/files",
            cache: false,  //-- 是否缓存
            async: true,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({"path":dir}),
            dataType: "json",
            success: function (e) {
            },
            complete:function(message){
                //alert(message.responseText);
                addHerf(message.responseText);
            },
            error: function (message) {
            }
        });
    }


    /**
    *当目被点击时，加载该目录下的文件
    */
    function loadDirFiles(dirPath){
    debugger
            $("#files").empty();
            $("#dir").attr("value", dirPath);
            loadFiles();

    }

    //增加a 标签
    function addHerf(list) {
        var arr = JSON.parse(list);
        if (arr.length == 0) {
            $("#files").append("无可查看的文件。");
            return;
        }

        for (var i = 0; i < arr.length; i++) {
            var aherf ;
            if(arr[i].dir==true){

                aherf = '&nbsp;<a  style="text-decoration:underline;" href="javascript:void(0)" target="_self" onclick="loadDirFiles(\'' + arr[i].filePath + '\')"; >' + arr[i].fileName + '</a> <br>';
            }else{
                aherf = '&nbsp;<a  style="text-decoration:underline;" href="javascript:void(0)" target="_self" onclick="loadLog(\'' + arr[i].fileKey + '\')"; >' + arr[i].fileName + '</a> <br>';
            }


            $("#files").append(aherf);

        }

    }




    window.onload = function(){
        var favoriteDir = getCookie('favoriteDir');
        $("#dir").attr("value", favoriteDir);
        loadFiles();
    }




</script>

</body>
</html>